package util

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
)

type Jwt struct {
	//Prefix 	string 	`yaml.prefix`
	Prefix string `default:"Bearer; "`
}

type CustomClaims struct {
	OpenId string
	jwt.StandardClaims
}

var (
	Secret = "AAAAB3NzaC1yc2EAAAADAQABAAAAQQDHtZtmuqg+yDOTWQYxGbY4SHFZndLH7iI1db4PcUVTmM4vzBdsA+4tZctbiqqHt9CKmksRWVrG45nxyWQEdG0V"
)

func (j Jwt) ParsingToken(tokenString string) (*CustomClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(Secret), nil
	})

	if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
		return claims, nil
	} else {
		return nil, err
	}
}

func (j Jwt) GenerateToken(openId string) (string, error) {
	fmt.Println(openId)
	//生成token
	maxAge := 60 * 60 * 24
	customClaims := &CustomClaims{
		OpenId: openId, //用户id
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Add(time.Duration(maxAge) * time.Second).Unix(), // 过期时间，必须设置
			Issuer:    "Litter",                                                   // 非必须，也可以填充用户名，
		},
	}
	//采用HMAC SHA256加密算法
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, customClaims)
	tokenString, err := token.SignedString([]byte(Secret))
	if err != nil {
		fmt.Println(err)
		return tokenString, err
	}
	fmt.Printf("token: %v\n", tokenString)
	return tokenString, nil

}
